package org.shiki.hrm.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class HrmResourcesCommonConfig extends ResourceServerConfigurerAdapter {
	@Value("${oauth.resourceId}")
	private String resourceId;
	/**
	 * 配置token
	 * @param resources
	 * @throws Exception
	 */
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		resources.resourceId(resourceId);
//		RemoteTokenServices tokenServices = new RemoteTokenServices();
//		tokenServices.setClientId("admin");
//		tokenServices.setClientSecret("1");
//		tokenServices.setCheckTokenEndpointUrl("http://localhost:3010/oauth/check_token");
		// 设置token校验
//		resources.tokenServices(tokenServices);
		resources.tokenStore(tokenStore());
	}

	@Bean
	public TokenStore tokenStore() {
//		return new InMemoryTokenStore();
		JwtTokenStore jwtTokenStore = new JwtTokenStore(getJwtTokenConvert());
		return jwtTokenStore;
	}

	private final String KEY  = "gzjkljgjij";

	@Bean
	public JwtAccessTokenConverter getJwtTokenConvert() {
		JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
		// 设置签名密钥
		jwtAccessTokenConverter.setSigningKey(KEY);
		return jwtAccessTokenConverter;
	}

	/**
	 * http安全配置
	 * @param http
	 * @throws Exception
	 */
	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				// cliantId对应认证服务客户端
				.antMatchers("/**").access("#oauth2.hasAnyScope('hrm')")
				// 关闭跨域伪造检查
				.and().csrf().disable()
				// session设置为无状态,使用token时不记录数据
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
	}
}